package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"time"
)

var loger *log.Logger

func init() {
	file := "./" + time.Now().Format("20180102") + ".txt"
	logFile, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
	if err != nil {
		panic(err)
	}
	loger = log.New(logFile, "[qSkiptool]", log.LstdFlags|log.Lshortfile|log.LUTC) // 将文件设置为loger作为输出

}

func GetLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {

		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

func sayHello(w http.ResponseWriter, r *http.Request) {

	strLocalIP := GetLocalIP()
	str := fmt.Sprintln(strLocalIP, http.StatusOK)
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
	log.Println(str)
	version := os.Getenv("VERSION")
	w.Header().Set("name", version)
	for k, v := range r.Header {
		for _, value := range v {
			w.Header().Set(k, value)
		}
	}
	w.Write([]byte("hello,http server"))
	//将日志写入文件中
	loger.Println(str)
}

func Heathy(w http.ResponseWriter, r *http.Request) {

	strLocalIP := GetLocalIP()
	str := fmt.Sprintln(strLocalIP, http.StatusOK)
	log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
	log.Println(str)

	version := os.Getenv("Version")
	w.Header().Set("name", version)
	for k, v := range r.Header {
		for _, value := range v {
			w.Header().Set(k, value)
		}
	}
	w.Write([]byte("200"))
	loger.Println(str)
}

func path(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path == "/hello" {
		http.HandleFunc("/hello", sayHello)
	} else if r.URL.Path == "/heathz" {
		http.HandleFunc("/heathz", Heathy)
	} else {
		strLocalIP := GetLocalIP()
		str := fmt.Sprintln(strLocalIP, http.StatusForbidden)
		log.SetFlags(log.LstdFlags | log.Lshortfile | log.LUTC)
		log.Println(str)
		w.Write([]byte("403 no page"))
		loger.Println(str)
	}

}

func main() {

	http.HandleFunc("/", path)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("http server failed, err:%v\n", err)
		return
	}
}
